<?php
/*
 * @Author: 哲学家乔布斯 <wuyangii@qq.com>
 * @Date: 2022-10-20 21:41:37
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-11-07 22:37:15
 * @Descripttion: 商品管理
 */
namespace app\admin\controller\system;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\AddShortUrlResponseBody\data;
use think\Db;

class Goods extends \app\admin\controller\Common
{
    public function index(){
    
        return view();
    }

    public function list(){
        $limit = request()->param('limit') ?? 15;
        $page = request()->param('page');
        $page = $page ? ($page - 1) * $limit : 0;
        $search = request()->param();
       
        $query = (new \app\common\model\Goods())->where(['is_del' => 0]);

        isset($search['goods_title']) && $search['goods_title'] != "" ? $query->where("title like '%{$search['goods_title']}%'") : '';
        $query->order("id desc");
        $where = [];
        if(!empty($search['bus_id'])){
            $where['bus_id'] = $search['bus_id'];
        }
        $list = $query->limit($page, $limit)->where($where)->append(['cate_title'])->select();
        $count = $query->count();
        return self::successResult('',$list,$count);
    }

    public function add(){
     
        if (request()->isPost()) {
            $info = request()->param('info');
            $sku_data = request()->param('sku_data');
            Db::startTrans();
            try{
                $message = "订单创建失败,请重试";
                $process = true;
                $info['imgs'] = json_encode($info['imgs']);
                $info['content'] = json_encode($info['content']);
                $row =  Db::table("{$this->tdb}goods")->insertGetId($info);
                if(!$row){
                    $message = "添加商品失败";
                    $process = false;
                }
                foreach ($sku_data as $key => &$value) {
                        $value['goods_id'] = $row;
                }
          
                $row =  Db::table("{$this->tdb}goods_sku")->insertAll($sku_data);
                if(!$row){
                    $message = "添加sku失败";
                    $process = false;
                }
               
                if ($process !== false) {
                    Db::commit(); // 提交事务
                } else {
                    Db::rollback(); // 回滚事务
                }

            } catch (\Exception $e) {
                $process = false;
                $message = $e->getMessage();
                Db::rollback(); // 回滚事务
            }
            if ($process !== false) {
                return self::successResult("创建成功");
            } else {
                return self::errorResult($message);
            }
     
       
        } else {
            $cate = (new \app\common\model\GoodsCate())->lists();
            $this->assign("cate",$cate);
  
            return view();
        }

    }

    
    public function edit(){
     
        if (request()->isPost()) {
            $info = request()->param('info');
            $id = request()->param('id');
            $sku_data = request()->param('sku_data');
            $sku_data_update = request()->param('sku_data_update');
            $is_default = request()->param('is_default');
           
            Db::startTrans();
            try{
                $message = "订单创建失败,请重试";
                $process = true;
               
                // $info['content'] = json_encode($info['content']);
                if(isset($info['is_imgs_id']) &&$info['is_imgs_id'] != '-1'){
                    $imgs = ($info['imgs']);
                    $info['img'] = $imgs[$info['is_imgs_id']];
                }
                $info['is_imgs_id'] = isset($info['is_imgs_id']) && $info['is_imgs_id'] != '-1' ? $imgs[$info['is_imgs_id']]: '-1';
                $row =  (new \app\common\model\Goods())->save($info,['id' => $id]);
                if(!$row){
                    $message = "添加商品失败";
                    $process = false;
                }
                #修改已存在的sku
                foreach ($sku_data_update as $key => $value) {
                    $row = (new \app\common\model\GoodsSku())->save([
                        'sku_title' => $value['sku_title'],
                        'money_cost' => $value['money_cost'],
                        'money' => $value['money'],
                        'stock' => $value['stock'],
                    ],['id' => $value['id']]);
                }
              
               
                #增加不存在的sku
                if(!empty($sku_data)){
                    foreach ($sku_data as $key => $value) {
                        $row = (new \app\common\model\GoodsSku())->where(['id' => $is_default])->update([
                            'is_default' => 1,
                        ]);
                        $is_defaults = 0;
                        if(!$row && "xid_{$key}" == $is_default){
                            $is_defaults = 1;
                        }
                        $row = (new \app\common\model\GoodsSku())->save([
                            'sku_title' => $value['sku_title'],
                            'money_cost' => $value['money_cost'],
                            'money' => $value['money'],
                            'goods_id' => $id,
                            'stock' => $value['stock'],
                            'is_default' => $is_defaults
                        ]);
                    }
                }
                if ($process !== false) {
                    Db::commit(); // 提交事务
                } else {
                    Db::rollback(); // 回滚事务
                }

            } catch (\Exception $e) {
                $process = false;
                $message = $e->getMessage();
                Db::rollback(); // 回滚事务
            }
            if ($process !== false) {
                return self::successResult("修改成功");
            } else {
                return self::errorResult($message);
            }
           
        } else {
            $id = request()->param('id');


            $goods = (new \app\common\model\Goods())->append(['brand_title','car_title','goods_type_title','imgs'])->where(['id' => $id])->find();
         
            $this->assign("goods",$goods);
          
            $sku = (new \app\common\model\GoodsSku())->where(['goods_id' => $id])->select();
            $this->assign("sku",$sku);
            $cate = (new \app\common\model\GoodsCate())->lists();
            $this->assign("cate",$cate);
            return view();
        }

    }
   public function get_level(){
         
        return self::successResult("",[
            0 => [
                'id' => 1, 'level' => 1 ,'name' => '1111',
            ]
        ]);
   }
   public function delete(){
        $id = request()->param('id');
        if (empty($id)) $this->error("请选择要删除的数据");
        $table = new \app\common\model\Goods();
        if (is_array($id)) {
            $id = implode(",", $id);
            $row = $table->whereIn('id', $id)->update(['is_del' => 1]);
        } else {
            $row = $table->where('id', $id)->update(['is_del' => 1]);
        }
        return $row ? self::successResult("成功") : self::errorResult("失败");
   }
  
   public function is_display()
   {
       $id = request()->param('id');
       $is_display = request()->param('is_display');
       if (empty($id)) $this->error("请选择要修改的数据");
       $table = new \app\common\model\Goods();
       $row = $table->where('id', $id)->update(['is_display' => $is_display]);
       return $row ? self::successResult() : self::errorResult('操作失败!请刷新后重试！');
   }
   public function import(){
        $execl_data = (new \app\common\controller\Upload())->execl();
        if($execl_data['state'] == 0){
            return json(['code' => 0, 'state' => 1,'data' => [],'msg' => $execl_data['msg']]);  
        }
        $filePath = ".".$execl_data['data']['url'];
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
        $spreadsheet = $reader->load($filePath); //载入excel表格
        $worksheet = $spreadsheet->getActiveSheet();
        $highestRow = $worksheet->getHighestRow(); // 总行数
        $lines = $highestRow - 1;
        if ($lines <= 0) {
            self::errorResult("Excel表格中没有数据");
        }
        $images = $worksheet->getDrawingCollection();
        $image_arr = []; 
        $dir = './uploads/images/' . date("Ymd") . "/";
        if (!is_dir($dir)) {
            mkdir(iconv("UTF-8", "GBK", $dir), 0777, true);
        }
      
        foreach ($images as $image) {
            if ($image instanceof \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing) {
                // 处理内存图片
            } else {
                $filename = $image->getPath();
                $imageData = file_get_contents($filename);
                $aa = time() . rand(1, 100) . '.' . $image->getExtension();
                $savePath =  $dir . date("Ymdhis") . $aa;
                file_put_contents($savePath, $imageData);
                $savePath = (new \app\common\controller\Upload())->COSUploadFile('images/' . date('Ymd') . '/' . $aa,  $savePath);
                $image_arr[$image->getCoordinates()] = $savePath['url'];
            }
        }
        $money = 0;
      
        for ($i = 2; $i <= $highestRow; $i++) {
            $title = $worksheet->getCellByColumnAndRow(1, $i)->getValue();
            if(empty($title)){
                break;
            }
            $cate_title = $worksheet->getCellByColumnAndRow(2, $i)->getValue();
            $sku_title = $worksheet->getCellByColumnAndRow(6, $i)->getValue();
            $money_cost = $worksheet->getCellByColumnAndRow(7, $i)->getValue();
            $money = $worksheet->getCellByColumnAndRow(8, $i)->getValue();
            $stock = $worksheet->getCellByColumnAndRow(9, $i)->getValue();
            $code = $worksheet->getCellByColumnAndRow(10, $i)->getValue();
      
            $img = '';
            $imgs = [];
            $content = [];
            if (!empty($image_arr["C{$i}"])) {
                $img = $image_arr["C{$i}"];
            }
            if (!empty($image_arr["D{$i}"])) {
                $imgs[] = $image_arr["D{$i}"];
            }
            if (!empty($image_arr["E{$i}"])) {
                $content[] = $image_arr["E{$i}"];
            }
            $cate_id = 0;
            if(!empty($cate_title)){
                $cate_titles = (new \app\common\model\GoodsCate())->where(['title' => $cate_title])->find();
                if(empty($cate_titles)){
                   $cate_id = (new \app\common\model\GoodsCate())->insertGetId([
                        'title' => $cate_title, 
                   ]); 
                }else{
                    $cate_id = $cate_titles['id'];
                }
            }
       
            $goods_id = (new \app\common\model\Goods())->insertGetId([
                'title' => $title,
                'cate_id' => $cate_id,
                'introduce' => $title,
                'img' => $img,
                'imgs' => json_encode($imgs),
                'content' => json_encode($content),
                'code' => $code,
                'import_time' => date("YmdHi"),
            ]);
            (new \app\common\model\GoodsSku())->insert([
                'goods_id' => $goods_id,
                'sku_title' => $sku_title,
                'money_cost' => empty($money_cost) ? 0 :$money_cost,
                'money' => empty($money) ? 0 :$money,
                'stock' => empty($stock) ? 0 :$stock ,
                'import_time' => date("YmdHi"),
      
            ]);
          
        }

        return self::successResult("成功");

   }
 
}
